package com.jianzong.lingxuan.interceptor;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.jianzong.lingxuan.contst.GlobalConsts;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 日志拦截器
 */
@Slf4j
public class LogInterceptor implements HandlerInterceptor {

    private static final String POST = "POST";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        MDC.put(GlobalConsts.TRACE_KEY, IdUtil.simpleUUID());
        String paramStr;
        // TODO: RequestBody的参数暂未考虑
        if (POST.equals(request.getMethod())) {
            Map<String, String[]> paramMap = request.getParameterMap();
            Map<String, Object> params = new HashMap<>(paramMap.size());
            paramMap.forEach((k, v) -> params.put(k, (v != null && v.length == 1) ? v[0] : v));
            paramStr = JSONUtil.toJsonStr(params);
        } else {
            paramStr = request.getQueryString();
        }
        log.info("{}|{}|{}", request.getMethod(), request.getRequestURI(), paramStr);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.clear();
    }

}
